<?php

namespace App\Http\Controllers\Dynamic;

use App\Models\Dynamic\BloodThreshold;
use App\Models\Dynamic\Medicalrecord;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;

class BloodThresholdController extends ApiController
{

    protected $blood_threshold;
    protected $request;
    protected $user;

    /**
     * GlucoseController constructor.
     * @param \App\Models\Dynamic\BloodThreshold $blood_threshold
     * @param \Illuminate\Http\Request $request
     */


    public function __construct(BloodThreshold $blood_threshold, User $user,
                                Request $request)
    {
        parent::__construct();

        $this->blood_threshold = $blood_threshold;
        $this->user = $user;
        $this->request = $request;
    }

    /**
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function store()
    {
        $this->validate($this->request, [
            'gettimetype' => 'numeric|min:0',
            'greenlow' => 'numeric |min:0',
            'greenhigh' => 'numeric |min:0',
            'yellowlow' => 'numeric |min:0',
            'yellowhigh' => 'numeric |min:0',
            'redlow' => 'numeric |min:0',
            'redhigh' => 'numeric |min:0',
            'user_id' => 'required|integer'
        ]);

        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);

        $medicalRecord = Medicalrecord::where('userbaseid', '=', $user->id)->select('status', 'id', 'userbaseid')->first();

        $usertype = 2;
        if (empty($medicalRecord)) {
            $usertype = 1;
        } else {
            if ($medicalRecord->status != '1') {
                $usertype = 1;
            }
        }


        $this->blood_threshold->fill($this->request->input());
        $this->blood_threshold->usertype = $usertype;
        $this->blood_threshold->userbaseid = $user->id;
        $this->blood_threshold->sceneid = $user->hospital_id;

        $this->blood_threshold->save();


        return $this->response(['id' => $this->blood_threshold->id]);
    }



}
